<template>
  <div style="position: fixed; top: 0; left: 0; margin: 20px;">
    <router-link
      to="/found"
      class="custom-link"
    >
      <el-button
        color="#626aef"
        :dark="isDark"
      >返回首页</el-button>
    </router-link>
  </div>
  <div v-if="sessionToken!==null">
    <div class="user-profile">
      <h2 class="profile-heading">个人中心</h2>
      <div class="user-info">
        <div>
          <p class="username">用户名: {{ currentUser.username }}</p>
          <button
            class="logout-btn"
            @click="logout"
          >退出登录</button>
        </div>
      </div>
      <div class="user-details">
        <!-- 显示用户邮箱 -->
        <p class="user-detail"><span class="detail-label">邮箱:</span>
          {{ currentUser.email }}</p>
        <!-- 显示用户手机号 -->
        <p class="user-detail"><span class="detail-label">手机号:</span>
          {{ currentUser.mobilePhoneNumber }}</p>
      </div>
    </div>

    <div class="card-container">
      <h2>失物招领帖子：</h2>
      <div v-if="foundPosts.length === 0">暂无失物招领帖子</div>
      <el-card
        v-for="post in foundPosts"
        :key="post.objectId"
        style="max-width: 430px"
        class="custom-card"
        shadow="hover"
      >
        <h4 class="card-title">
          {{ post.title }}
        </h4>
        <img
          src="../assets/erji.png"
          style="width: 100%"
        />
        <div>
          <p>{{ post.content }}</p>
          <el-button
            @click="deletePost('found', post.objectId)">删除帖子</el-button>
        </div>
      </el-card>

      <h2>寻物启事帖子：</h2>
      <div v-if="lostPosts.length === 0">暂无寻物启事帖子</div>
      <el-card
        v-for="post in lostPosts"
        :key="post.objectId"
        style="max-width: 430px"
        class="custom-card"
        shadow="hover"
      >
        <h4 class="card-title">
          {{ post.title }}
        </h4>
        <img
          src="../assets/erji.png"
          style="width: 100%"
        />
        <div>
          <p>{{ post.content }}</p>
          <el-button @click="deletePost('lost', post.objectId)">删除帖子</el-button>
        </div>
      </el-card>
    </div>
  </div>
  <div
    v-else
    class="user-auth"
  >
    <div class="auth-section">
      <h2>用户登录</h2>
      <div class="input-group">
        <label for="loginUsername">用户名：</label>
        <input
          type="text"
          id="loginUsername"
          v-model="loginForm.username"
          placeholder="请输入用户名"
        >
      </div>
      <div class="input-group">
        <label for="loginPassword">密码：</label>
        <input
          type="password"
          id="loginPassword"
          v-model="loginForm.password"
          placeholder="请输入密码"
        >
      </div>
      <button
        @click="login"
        class="auth-button"
      >登录</button>
    </div>

    <div class="auth-section">
      <h2>用户注册</h2>
      <div class="input-group">
        <label for="registerUsername">用户名：</label>
        <input
          type="text"
          id="registerUsername"
          v-model="registerForm.username"
          placeholder="请输入用户名"
        >
      </div>
      <div class="input-group">
        <label for="registerPassword">密码：</label>
        <input
          type="password"
          id="registerPassword"
          v-model="registerForm.password"
          placeholder="请输入密码"
        >
      </div>
      <div class="input-group">
        <label for="registerEmail">邮箱：</label>
        <input
          type="email"
          id="registerEmail"
          v-model="registerForm.email"
          placeholder="请输入邮箱"
        >
      </div>
      <div class="input-group">
        <label for="registerPhone">手机号：</label>
        <input
          type="text"
          id="registerPhone"
          v-model="registerForm.mobilePhoneNumber"
          placeholder="请输入手机号"
        >
      </div>
      <button
        @click="register"
        class="auth-button"
      >注册</button>
    </div>

    <div class="guest-browse">
      <router-link
        to="/found"
        class="custom-link"
      >
        <el-button
          color="#626aef"
          :dark="isDark"
        >游客浏览</el-button>
      </router-link>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue';
// import Bmob from 'bmob-js-sdk';
import { useRouter } from 'vue-router'
import router from '@/router';
import { ElMessage } from 'element-plus'
export default {
  data () {
    return {
      currentUser: null,
      foundPosts: [],
      lostPosts: [],
    };
  },
  created () {
    // 在组件创建时获取当前用户信息
    if (this.sessionToken) {
      this.getCurrentUser();
    }
  },
  methods: {
    getCurrentUser () {
      if (this.sessionToken) {
        //  currentUser 是在 data 中存储的用户信息对象
        this.currentUser = Bmob.User.current();
      } else {
        console.log('用户未登录');
      }
    },
    fetchPosts (type) {
      if (this.sessionToken) {
        const currentUser = Bmob.User.current();
        const query = Bmob.Query(type === 'found' ? 'found' : 'lost');
        query.equalTo('userId', '==', currentUser.objectId); // 根据用户表中的 objectId 进行匹配
        query.find().then(posts => {
          if (type === 'found') {
            this.foundPosts = posts;
          } else {
            this.lostPosts = posts;
          }
        }).catch(error => {
          console.error('获取帖子失败:', error);
        });
      }
    },
    deletePost (type, postId) {
      if (this.sessionToken) {
        const query = Bmob.Query(type === 'found' ? 'found' : 'lost');
        query.destroy(postId).then(() => {

          // console.log('帖子删除成功');
          ElMessage.success('删除成功！');
          // 删除成功后刷新帖子列表
          this.fetchPosts(type);
        }).catch(error => {
          ElMessage.success('删除失败！');
          // console.error('删除帖子失败:', error);
        });
      }
    }
  },
  mounted () {
    const sessionToken = localStorage.getItem('sessionToken');
    if (sessionToken) {
      // 如果sessionToken存在，则用户已登录，可以执行相应的操作
      console.log('用户已登录，sessionToken:', sessionToken);
    } else {
      console.log('用户未登录');
      // router.push('login');
    };
    this.fetchPosts('found');
    this.fetchPosts('lost');
  },
  setup () {
    //首先在setup中定义
    const router = useRouter();
    const sessionToken = ref(localStorage.getItem('sessionToken'));
    const loginForm = ref({
      username: '',
      password: ''
    });
    const registerForm = ref({
      username: '',
      password: '',
      email: '',
      mobilePhoneNumber: '',
    });


    const login = () => {
      Bmob.User.login(loginForm.value.username, loginForm.value.password).then(res => {
        console.log('登录成功:', res);
        localStorage.setItem('sessionToken', res.sessionToken);
        let currentUser = Bmob.User.current();
        // console.log('当前用户信息:', currentUser);
        ElMessage.success('登录成功！');
        router.push('/found');
        // console.log('跳转页面')
      }).catch(err => {
        ElMessage.success('登录失败，请检查用户名和密码');
        // console.log('登录失败:', err);
      });
    };
    //注册用户
    const register = async () => {
      try {
        const res = await Bmob.User.register(registerForm.value);
        console.log('注册成功:', res);
        clearRegisterForm();
        ElMessage.success('注册成功！');
      } catch (err) {
        console.error('注册失败:', err);
        ElMessage.success('注册失败！');
      }
    };
    const clearRegisterForm = () => {
      // 将注册表单的各个字段重置为空字符串
      registerForm.value.username = '';
      registerForm.value.password = '';
      registerForm.value.email = '';
      registerForm.value.mobilePhoneNumber = '';
    };
    //退出登录
    const logout = async () => {
      try {
        await Bmob.User.logout();
        sessionToken.value = null;
        localStorage.removeItem('sessionToken');
        ElMessage.success('退出成功！');
        // console.log('退出成功')
        // console.log('当前sessionToken状态:', sessionToken.value);
        router.push('/login');
      } catch (error) {
        ElMessage.success('退出失败！');
        console.error('退出登录失败:', error);
      }
    };
    return {
      sessionToken,
      loginForm,
      registerForm,
      login,
      logout,
      register
    };
  },
};
</script>

<style>
.card-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}
.custom-card {
  width: 350px;
  transition: all 0.5s;
  border: 1px solid transparent;
  border-radius: 15px;
  box-shadow: 5px 5px 0 0 rgba(0, 0, 0, 0.2);
  margin: 10px 0;
}
.custom-card .card-title {
  color: #333; /* 设置文字颜色 */
  text-decoration: none;
}
.custom-card:hover .card-title {
  color: #00aeff; /* 设置悬停时文字颜色 */
}
.el-card:hover {
  margin-top: -5px;
}
.card-link {
  text-decoration: none; /* 取消链接默认下划线 */
  color: inherit; /* 继承父元素的文字颜色 */
}
.user-profile {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.profile-heading {
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
}

.user-info {
  margin-bottom: 10px;
}

.username {
  margin-right: 10px;
  font-weight: bold;
  font-size: 16px;
  color: #333;
}

.logout-btn {
  background-color: #f44336;
  color: #fff;
  border: none;
  padding: 8px 16px;
  border-radius: 3px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
}

.logout-btn:hover {
  background-color: #d32f2f;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.user-detail {
  font-size: 14px;
  color: #666;
}

.detail-label {
  font-weight: bold;
  margin-right: 5px;
}
.user-auth {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.auth-section {
  margin-bottom: 20px;
}

.auth-section h2 {
  margin-bottom: 10px;
  font-size: 20px;
  color: #333;
}

.input-group {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.input-group label {
  width: 100px;
  display: block;
  margin-bottom: 5px;
  font-size: 16px;
  color: #666;
  margin-right: 5px; /* 调整标签与输入框之间的间距 */
}

.input-group input[type="text"],
.input-group input[type="password"],
.input-group input[type="email"] {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 16px;
}

.auth-button {
  background-color: #626aef;
  color: #fff;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
}

.auth-button:hover {
  background-color: #4148a7;
}

.custom-link {
  text-decoration: none;
}

.guest-browse {
  margin-top: 20px;
}
</style>